# -*- coding UTF-8 -*-

import kivy

from kivy.uix.boxlayout import BoxLayout
from ui.hat_widget import HatWidget
from kivy.app import App

import model.gamestate


class PlayerListElement(BoxLayout):
    def __init__(self, root, player, idx, **kwargs):
        self.root = root
        self.player = player
        self.idx = idx
        super(PlayerListElement, self).__init__(**kwargs)

    def change_name(self, name):
        name = name.strip()
        self.player.name = name
        self.root.update()


class EditPlayers(HatWidget):
    def __init__(self, gamestate, presenter, **kwargs):
        super(EditPlayers, self).__init__(presenter, **kwargs)
        self.gamestate = gamestate
        self.players_list.height = len(self.gamestate.players.players) * \
            self.width * 0.6
        self.text_inputs = []
        idx = 0
        for player in self.gamestate.players.players:
            player_elem = PlayerListElement(self, player, idx)
            self.text_inputs.append(player_elem)
            self.players_list.add_widget(player_elem)
            idx += 1

    def next_screen(self):
        self.presenter.change_phase(model.gamestate.Phase.FROM_TO)

    def go_back(self):
        self.presenter.change_phase(model.gamestate.Phase.QUICK_GAME_SETTINGS)

    def update(self):
            is_wrong_exist = False
            for text_input1 in self.text_inputs:
                is_wrong_name = False
                for text_input2 in self.text_inputs:
                    if (not(text_input1 == text_input2) and
                       text_input1.player.name == text_input2.player.name):
                        is_wrong_name = True
                if is_wrong_name:
                    text_input1.text_input.background_color = [.6, 0, 0, 1]
                    text_input2.text_input.background_color = [.6, 0, 0, 1]
                    is_wrong_exist = True
                else:
                    text_input1.text_input.background_color = [1, 1, 1, 1]
                    text_input2.text_input.background_color = [1, 1, 1, 1]
            self.next_button.enabled = not is_wrong_exist

    def change_line(self, idx):
        idx = (idx + 1) % len(self.text_inputs)
        self.text_inputs[idx].text_input.focus = True
        self.text_inputs[idx].text_input.select_all()
